/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { BaseCommand, pickedFaceData, pickedLineData } from '@amcax/base';
import {
  BasePickInputRJSFFormat,
  PickInputRJSFFormat,
} from '@app-cad/common/components/command-form/constants';
import { PickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { composeFormat } from '@app-cad/common/components/command-form/utils';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { getIdOfPickedObj } from '@app-cad/common/utils/render';
import { previewer } from '@app-cad/module';
import { wsApi } from '@app-cad/server';
import { FeaturedCmdDialogParams } from '@app-cad/types';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import i18n from 'i18next';
import { useMemo, useState } from 'react';

type FormData = {
  profile: (pickedLineData | pickedFaceData)[];
};

type SweepParams = {
  mode: 'fuse';
  profile: string[];
};

function Loft({ title, onClose, placement, props }: FeaturedCmdDialogParams) {
  const [formData, setFormData] = useState<FormData>({
    profile: [],
  });
  const { picker } = useTools();

  useAsyncEffect(async () => {
    if (props == null) {
      setFormData({
        profile: [],
      });
      return;
    }

    const { profile } = props.params;

    await initEditDependency([...profile]);

    const profileObj =
      profile?.length > 0 &&
      profile.map(
        (dxid) =>
          picker.generatePickObjByPickID(dxid) as
            | pickedLineData
            | pickedFaceData,
      );

    const datas = {
      profile: profileObj,
    };

    setFormData(datas);
  }, []);

  useAsyncEffect(async () => {
    if (!isFormDataValid()) {
      previewer.clear();
      return;
    }
    await execute(true);
  }, [formData]);

  const isFormDataValid = () => {
    const { profile } = formData;

    return profile?.length > 1;
  };
  const finishValid = useMemo(isFormDataValid, [formData]);
  const execute = async (preview: boolean = false) => {
    const { profile } = formData;
    const profileIDs: string[] = profile.map((obj) => getIdOfPickedObj(obj));

    const params: SweepParams = {
      mode: 'fuse',
      profile: profileIDs,
    };
    const res =
      props == null
        ? await wsApi.createLoftFeature(params, preview)
        : await wsApi.setParams(props.shape, params, preview);

    if (preview) {
      await previewInCommand(res);
    }

    return res;
  };

  const checkAndFinish = async () => {
    if (!isFormDataValid()) {
      return;
    }

    execute();

    exit();
  };

  const exit = () => {
    previewer.clear();
    onClose();
  };

  // =================

  const schema: RJSFSchema = {
    properties: {
      profile: {
        type: 'array',
        items: {
          type: 'string',
          enum: [],
        },
        uniqueItems: true,
        format: composeFormat([
          PickInputRJSFFormat.MultiPickContours,
          BasePickInputRJSFFormat.MultiPickVertex,
        ]),
      },
    },
  };

  const { initEditDependency, previewInCommand } = useCommand('cmd-loft', {
    onClose,
    finishDraw: checkAndFinish,
  });

  return (
    <PickableCommandForm
      isFormDataValid={finishValid}
      disabled={false}
      onClose={exit}
      title={title}
      placement={placement}
      schema={schema}
      formData={formData}
      onChange={(v) => {
        setFormData(v);
      }}
      extraUiSchema={{
        profile: {
          'ui:placeholder': '请输入放样线',
          'ui:autofocus': true,
          'ui:options': {
            allowInfinitePlane: false,
            allowInfiniteLine: false,
          },
        },
      }}
      submitText='完成'
      onSubmit={checkAndFinish}
    />
  );
}

export const cmdLoft: BaseCommand = {
  id: 'CmdLoft',
  label: 'command.loft',
  icon: 'commands/feature/loft',
  create: (label, onClose, props) => (
    <Loft
      title={i18n.t(label)}
      onClose={onClose}
      props={props}
    />
  ),
};
